package com.hl.sfzy.controller;

import com.github.pagehelper.PageInfo;
import com.hl.sfzy.entity.Request;
import com.hl.sfzy.entity.User;
import com.hl.sfzy.service.UserService;
import com.hl.sfzy.utils.MD5Util;
import com.hl.sfzy.utils.R;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService userService;
//	添加
	@PostMapping("/add")
	private R add(@RequestBody User user) {
		int result = userService.add(user);
		if (result != 0) {
			return R.ok(result);
		} else {
			return R.fail("添加失败");
		}
	}
//	修改
	@PutMapping("/edit")
	private R edit(@RequestBody User user) {
		int result = userService.edit(user);
		if (result != 0) {
			return R.ok(result);
		} else {
			return R.fail("修改失败");
		}
	}

//	根据id删除
	@DeleteMapping("/remove")
	private R remove(Integer userId) {
		int result = userService.remove(userId);
		if (result != 0) {
			return R.ok(result);
		} else {
			return R.fail("删除失败");
		}
	}
//	批量删除
	@DeleteMapping("/removeBatch")
	private R removeBatch(Integer[] userIds) {
		int result = userService.removeBatch(userIds);
		if (result != 0) {
			return R.ok(result);
		} else {
			return R.fail("删除失败");
		}
	}
//	查询所有
	@GetMapping("/find")
	private R find() {
		List<User> users = userService.find();
		return R.ok(users);
	}
// 	分页查询
	@GetMapping("/findByPage")
	private R findByPage(
			@RequestParam(required = false ,defaultValue = "1")int pageNum,
			@RequestParam(required = false,defaultValue = "5") int pageSize, User user) {
		PageInfo<User> users = userService.findByPage(pageNum, pageSize, user);
		return R.ok(users);
	}
//	根据id查询
	@GetMapping("/findById")
	private R findById(Integer userId) {
		User user = userService.findById(userId);
		return R.ok(user);
	}

//	登陆
	@GetMapping("/login")
	public R login(String userUserName, String userPassword){
		User user= userService.login(userUserName, userPassword);
		if (user!=null){
			System.out.println(user);
			return R.ok(user);
		}else{
			return R.fail("账号或密码错误");
		}
	}
//   修改密码
	@PutMapping("/updatePassword")
	public R updatePassword(@RequestBody Request request) {
		int code = userService.updatePassword(request);
		if (code == 1){
			return R.ok("修改成功");
		}if (code == -2 ){
			return R.fail("旧密码错误");
		}else{
			return R.fail("修改失败");
		}

	}

}
